import axios from 'axios'
import Toast from 'vux/src/plugins/toast/index.js'
import router from '.././router'

// 创建axios实例
const service = axios.create({
  baseURL: '/API/', // api的base_url
  timeout: 10000                  // 请求超时时间
})

// request拦截器
service.interceptors.request.use(config => {
  const jwtToken = localStorage.getItem('jwtToken')
  if (jwtToken) {
    config.headers.Authorization = 'Bearer ' + jwtToken
  }

  const uid = localStorage.getItem('uid')
  if (uid) {
    if (config.data) {
      config.data.uid = uid
    } else {
      config.data = {}
      config.data.uid = uid
    }
  }
  if (config.data) {
    if (!config.data.openid) {
      config.data.openid = localStorage.getItem('openid')
    }
  } else {
    config.data = {}
    if (!config.data.openid) {
      config.data.openid = localStorage.getItem('openid')
    }
  }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => {
    if (response.status === 200) {
      return response.data
    } else {
      return Promise.reject(response)
    }
  },
  error => {
    // debugger
    if (error.response.status === 401) { // 无效token
      sessionStorage.removeItem('jwtToken')
      router.push('login')
    }
    Toast.show({
      text: error.response.data.message,
      type: 'warn',
      timw: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
